package com.seven.monior;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.TrafficStats;
import android.os.Debug.MemoryInfo;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.seven.monior.AppInfo.Global;
import com.seven.monior.TaskInfo.ProcessRecord;
import com.seven.monior.TaskInfo.ProcessState;
import com.seven.monior.TaskInfo.TaskInfo;

public class MonitorService extends Service {
	public static boolean InitialFinished = false;
	public static boolean Reseting = false;
	public static boolean SyncingDB = false;
	public static boolean Monitor_Visible;
	private TelephonyManager tm;
	private ArrayList<TaskInfo> mTaskInfos;
	private ActivityManager am;
	private DatabaseHelper databaseHelper;
	private Timer updateTimer;
	private Timer syncDBTimer;
	private Timer recordProcessTimer;
	private ArrayList<ProcessRecord> pRecords = new ArrayList<ProcessRecord>();

	private boolean m_bIsWifiConnected = false;
	private boolean m_bIsNetworkActiveChanged = false;
	private boolean m_bListUpdated = false;
	private boolean m_bScreenOff = false;
	private ConnectionMonitor mConnectionReceiver;

	public void onCreate() {
		Toast.makeText(this, "Monitor Service is Created", Toast.LENGTH_LONG)
				.show();
		mTaskInfos = Global.taskInfoList;
		databaseHelper = new DatabaseHelper(this);
		if (Global.pm == null)
			Global.pm = getPackageManager();

		am = Global.am;
		if (am == null)
			am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);

		tm = Global.mTelephonyMgr;
		if (tm == null)
			tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

		// m_nCurrentMobileNetwork = getCurrentNetworkType();
		// Log.d("network type", String.valueOf(m_nCurrentMobileNetwork));
		tm.listen(new PhoneStateListener() {
			public void onDataActivity(int direction) {
				Log.d("DataActivity", "DataActivity Changed");
				m_bIsNetworkActiveChanged = true;
				// switch (direction) {
				// case TelephonyManager.DATA_ACTIVITY_NONE:
				// case TelephonyManager.DATA_ACTIVITY_DORMANT:
				// m_bIsNetworkActive = false;
				// break;
				// default:
				// m_bIsNetworkActive = true;
				// break;
				// }
			}

		}, PhoneStateListener.LISTEN_DATA_ACTIVITY);

		loadSharePreference();

		InitData();

		updateTimer = new Timer("taskTrafficRefresh");
		updateTimer.schedule(doRefresh, 0L, 10000L);

		syncDBTimer = new Timer("taskSyncDB");
		syncDBTimer.schedule(doSyncDB, 10000L, 60000L);
		// syncDBTimer.schedule(doSyncDB, 10000, 20000);

		recordProcessTimer = new Timer("recordProcessTimer");
		// recordProcessTimer.scheduleAtFixedRate(doRecordProcess, 0, 1000);

		// startForeground(, );

	}

	public void onStart(Intent intent, int startId) {
		m_bIsWifiConnected = !mobile_IsConnected();

		mConnectionReceiver = new ConnectionMonitor();
		startMonitoringConnection();
		// RefreshList();

		Toast.makeText(this, "Monitor Service is Runnig", Toast.LENGTH_LONG)
				.show();

		Notification notification = new Notification(R.drawable.icon,
				"Moniter Service is Running", System.currentTimeMillis());
		PendingIntent contentIntent = PendingIntent.getService(
				getApplicationContext(), 0, intent, 0);
		notification.setLatestEventInfo(this, "SEVEN Monitor",
				notification.tickerText, contentIntent);
		startForeground(0, notification);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		stopMonitoringConnection();

		super.onDestroy();
	}

	public void InitData() {
		InitialFinished = false;
		// SQLiteDatabase db = databaseHelper.getWritableDatabase();
		// db.delete("apps", null, null);
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				initListFromDB(databaseHelper);
				databaseHelper.close();
				InitialFinished = true;
			}
		}).start();
	}

	private TimerTask doRefresh = new RefreshTimerTask();

	private TimerTask doSyncDB = new TimerTask() {

		@Override
		public void run() {

			if (!InitialFinished)
				return;
			if (Monitor_Visible)
				return;
			if (m_bListUpdated) {
				SyncDB();
				m_bListUpdated = false;
				// Log.e("Service", "SyncDB");
				// Log.e("Service", String.valueOf(SyncingDB));
			} else {
				Log.e("Service", "List no change");
			}
		}
	};

	private TimerTask doRecordProcess = new TimerTask() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			RecordProcess();
		}
	};

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	private void RecordProcess() {
		// pRecords.clear();
		ArrayList<ProcessRecord> new_pRecords = new ArrayList<ProcessRecord>();
		ArrayList<Integer> pids = new ArrayList<Integer>();
		List<RunningAppProcessInfo> rInfos = am.getRunningAppProcesses();
		for (int i = 0; i < rInfos.size(); i++) {
			RunningAppProcessInfo rInfo = rInfos.get(i);
			int nPid = rInfo.pid;
			int nUid = rInfo.uid;
			ProcessRecord pRecord = new ProcessRecord(nPid, nUid);
			ProcessState pState = new ProcessState(nPid);
			pRecord.setCpuTime(pState.getCpuTime());
			// pRecord.setCpuSTime(pState.getCpuSTime());
			// pRecord.setCpuUTime(pState.getCpuUTime());
			// Log.i("processname", "uid: " + nUid + " pid: " + nPid + " name: "
			// + pState.getCommand());
			new_pRecords.add(pRecord);
			pids.add(nPid);
		}

		int[] nPids = new int[pids.size()];
		for (int i = 0; i < nPids.length; i++) {
			nPids[i] = pids.get(i);
		}
		pids.clear();
		MemoryInfo[] memoryInfos = am.getProcessMemoryInfo(nPids);

		for (int i = 0; i < new_pRecords.size(); i++) {
			ProcessRecord new_pRecord = new_pRecords.get(i);
			MemoryInfo memoryInfo = memoryInfos[i];
			new_pRecord.setMemory(memoryInfo.getTotalPss());
			ProcessRecord old_pRecord = find_old_proc(new_pRecord.getPid(),
					new_pRecord.getUid());
			if (old_pRecord != null) {
				double oldCpuTime = old_pRecord.getCpuTime();
				new_pRecord.setLastCpuTime(oldCpuTime);
			} else {

			}

		}
		pRecords.clear();
		pRecords = new_pRecords;

		for (int i = 0; i < mTaskInfos.size(); i++) {
			TaskInfo tInfo = mTaskInfos.get(i);
			tInfo.setMemory(0);
			boolean bFound = false;
			for (int j = 0; j < pRecords.size(); j++) {
				ProcessRecord pRecord = pRecords.get(j);
				if (tInfo.getUID() != pRecord.getUid()) {
					continue;
				} else {
					bFound = true;
					double oldCpuTime = tInfo.getTotalCpuTime();
					double newCpuTime = 0;
					if (pRecord.getLastCpuTime() <= 0)
						newCpuTime = oldCpuTime;
					else {
						newCpuTime = oldCpuTime + pRecord.getCpuTime()
								- pRecord.getLastCpuTime();
					}
					tInfo.setTotalCpuTime(newCpuTime);

					tInfo.setMemory(tInfo.getMemory() + pRecord.getMemory());
				}
			}
			if (bFound) {
				tInfo.setIsRunning(true);
			} else {
				tInfo.setIsRunning(false);
			}

		}

	}

	private ProcessRecord find_old_proc(int pid, int uid) {
		for (int i = 0; i < pRecords.size(); i++) {
			ProcessRecord record = pRecords.get(i);
			if (record.getPid() == pid && record.getUid() == uid)
				return record;
		}

		return null;
	}

	private void loadSharePreference() {
		// sharepreference

		SharedPreferences sPreferences = getSharedPreferences(Global.PREFS,
				Activity.MODE_PRIVATE);
		long currentTime = System.currentTimeMillis();
		long sinceTimeDate = sPreferences.getLong("since_time", currentTime);
		if (sinceTimeDate == currentTime) {
			SharedPreferences.Editor editor = sPreferences.edit();
			editor.putLong("since_time", currentTime);
			editor.commit();
		}
		long Total_Mobile_Rx = sPreferences.getLong("total_mobile_rx", 0L);
		long Total_Mobile_Tx = sPreferences.getLong("total_mobile_tx", 0L);
		long last_Mobile_Rx = TrafficStats.getMobileRxBytes();
		long last_Mobile_Tx = TrafficStats.getMobileTxBytes();

		// long last_Mobile_Rx = sPreferences.getLong("last_mobile_rx", 0L);
		// long last_Mobile_Tx = sPreferences.getLong("last_mobile_tx", 0L);

		Global.SINCE_TIMESTAMP = new Date(sinceTimeDate);
		Global.Total_Mobile_Rx = Total_Mobile_Rx;
		Global.Total_Mobile_Tx = Total_Mobile_Tx;

		Global.last_Mobile_Rx = last_Mobile_Rx;
		Global.last_Mobile_Tx = last_Mobile_Tx;
	}

	private void initListFromDB(DatabaseHelper dbHelper) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();

		Cursor cs = db.query("apps", null, null, null, null, null, null);
		mTaskInfos.clear();
		if (cs.moveToFirst()) {
			List<RunningAppProcessInfo> rInfos = am.getRunningAppProcesses();
			ContentValues cv = new ContentValues();
			cv.put("is_running", 1);
			for (int i = 0; i < rInfos.size(); i++) {
				String where = "uid=" + rInfos.get(i).uid;
				db.update("apps", cv, where, null);
			}
		} else {
			Reseting = true;
			Intent intent = new Intent(Global.ACTION_RESET);
			sendBroadcast(intent);
		}
		cs.close();
		while (Reseting) {
			try {
				Thread.sleep(100L);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		cs = db.query("apps", null, null, null, null, null, null);
		if (cs.moveToFirst()) {
			int nIndexOf_isRunning = cs.getColumnIndex("is_running");
			do {

				int nUID = cs.getInt(cs.getColumnIndex("uid"));
				int nIs_Running = cs.getInt(nIndexOf_isRunning);
				boolean bIs_Running = false;
				if (nIs_Running == 0)
					bIs_Running = false;
				else {
					bIs_Running = true;
				}
				Long lMobile_Rx = cs.getLong(cs
						.getColumnIndex("mobile_received"));
				Long lMobile_Tx = cs.getLong(cs.getColumnIndex("mobile_sent"));
				Long lTotal_Rx = cs
						.getLong(cs.getColumnIndex("total_received"));
				Long lTotal_Tx = cs.getLong(cs.getColumnIndex("total_sent"));
				double dCpuTime = cs.getDouble(cs.getColumnIndex("cputime"));

				TaskInfo tInfo = new TaskInfo(nUID, bIs_Running, lMobile_Rx,
						lMobile_Tx, lTotal_Rx, lTotal_Tx);

				tInfo.m_lMobile_last_Rx = TrafficStats.getUidRxBytes(nUID);
				tInfo.m_lMobile_last_Tx = TrafficStats.getUidTxBytes(nUID);
				tInfo.setTotalCpuTime(dCpuTime);

				mTaskInfos.add(tInfo);

			} while (cs.moveToNext());
			RecordProcess();
			// Collections.sort(mTaskInfos, sortByBytes);
		}
		cs.close();
		db.close();
		Intent intent = new Intent(Global.ACTION_UPDATE_UI);
		sendBroadcast(intent);
	}

	private void RefreshList() {

		if (!m_bIsWifiConnected) {
			List<RunningAppProcessInfo> rInfos = am.getRunningAppProcesses();

			for (int j = 0; j < rInfos.size(); j++) {
				RunningAppProcessInfo rInfo = rInfos.get(j);

				boolean bCatch = false;
				Long lMobile_now_Rx = 0L;
				Long lMobile_now_Tx = 0L;
				Long lOther_now_Rx = 0L;
				Long lOther_now_Tx = 0L;
				Long lTotal_now_Rx = 0L;
				Long lTotal_now_Tx = 0L;
				lTotal_now_Rx = TrafficStats.getUidRxBytes(rInfo.uid);
				lTotal_now_Tx = TrafficStats.getUidTxBytes(rInfo.uid);
				if (!m_bIsWifiConnected) {
					lMobile_now_Rx = lTotal_now_Rx;
					lMobile_now_Tx = lTotal_now_Tx;

				} else {
					lOther_now_Rx = lTotal_now_Rx;
					lOther_now_Tx = lTotal_now_Tx;
				}

				for (int i = mTaskInfos.size() - 1; i >= 0; i--) {
					TaskInfo tInfo = mTaskInfos.get(i);

					if (tInfo.getUID() == rInfo.uid) {
						tInfo.setPID(rInfo.pid);
						bCatch = true;
						Long lMobile_Rx = tInfo.m_lMobile_Rx;
						Long lMobile_last_Rx = tInfo.m_lMobile_last_Rx;
						Long lMobile_Tx = tInfo.m_lMobile_Tx;
						Long lMobile_last_Tx = tInfo.m_lMobile_last_Tx;

						// Long lOther_Rx = tInfo.m_lOther_Rx;
						// Long lOther_last_Rx = tInfo.m_lOther_last_Rx;
						// Long lOther_Tx = tInfo.m_lOther_Tx;
						// Long lOther_last_Tx = tInfo.m_lOther_last_Tx;
						//
						// Long lTotal_Rx = tInfo.m_lTotal_Rx;
						// Long lTotal_last_Rx = tInfo.m_lTotal_last_Rx;
						// Long lTotal_Tx = tInfo.m_lTotal_Tx;
						// Long lTotal_last_Tx = tInfo.m_lTotal_last_Tx;

						if (lMobile_now_Rx - lMobile_last_Rx >= 0
								&& lMobile_last_Rx > 0) {
							lMobile_Rx += lMobile_now_Rx - lMobile_last_Rx;
							tInfo.m_lMobile_Rx = lMobile_Rx;
						}
						lMobile_last_Rx = lMobile_now_Rx;
						tInfo.m_lMobile_last_Rx = lMobile_last_Rx;

						if (lMobile_now_Tx - lMobile_last_Tx >= 0
								&& lMobile_last_Tx > 0) {
							lMobile_Tx += lMobile_now_Tx - lMobile_last_Tx;
							tInfo.m_lMobile_Tx = lMobile_Tx;
						}
						lMobile_last_Tx = lMobile_now_Tx;
						tInfo.m_lMobile_last_Tx = lMobile_last_Tx;
						//
						// if (lOther_now_Rx - lOther_last_Rx >= 0
						// && lOther_last_Rx > 0) {
						// lOther_Rx += lOther_now_Rx - lOther_last_Rx;
						// tInfo.m_lOther_Rx = lOther_Rx;
						// }
						// lOther_last_Rx = lOther_now_Rx;
						// tInfo.m_lOther_last_Rx = lOther_last_Rx;
						//
						// if (lOther_now_Tx - lOther_last_Tx >= 0
						// && lOther_last_Tx > 0) {
						// lOther_Tx += lOther_now_Tx - lOther_last_Tx;
						// tInfo.m_lOther_Tx = lOther_Tx;
						// }
						// lOther_last_Tx = lOther_now_Tx;
						// tInfo.m_lOther_last_Tx = lOther_last_Tx;
						//
						// if (lTotal_now_Rx - lTotal_last_Rx >= 0
						// && lTotal_last_Rx > 0) {
						// lTotal_Rx += lTotal_now_Rx - lTotal_last_Rx;
						// tInfo.m_lTotal_Rx = lTotal_Rx;
						// }
						// lTotal_last_Rx = lTotal_now_Rx;
						// tInfo.m_lTotal_last_Rx = lTotal_last_Rx;
						//
						// if (lTotal_now_Tx - lTotal_last_Tx >= 0
						// && lTotal_last_Tx > 0) {
						// lTotal_Tx += lTotal_now_Tx - lTotal_last_Tx;
						// tInfo.m_lTotal_Tx = lTotal_Tx;
						// }
						// lTotal_last_Tx = lTotal_now_Tx;
						// tInfo.m_lTotal_last_Tx = lTotal_last_Tx;

					}
				}
				if (!bCatch) {
					TaskInfo tInfo = new TaskInfo(rInfo.uid, true, 0L,
							lMobile_now_Rx, 0L, lMobile_now_Tx, 0L,
							lOther_now_Rx, 0L, lOther_now_Tx, 0L,
							lTotal_now_Rx, 0L, lTotal_now_Tx);
					mTaskInfos.add(tInfo);
					// tInfo.setPID(rInfo.pid);
					// tInfo.setPkgList(rInfo.pkgList);
					Log.d("ADD NEW TASKINFO", tInfo.getProcessName());
				}
			}
		}
		RecordProcess();
		// Collections.sort(mTaskInfos, sortByBytes);

		// setRunningState();
		updateTotalBytes();

		Intent intent = new Intent(Global.ACTION_UPDATE_UI);
		sendBroadcast(intent);

		// handler.post(doUpdateUI);
	}

	private void updateTotalBytes() {

		long currentMobile_Rx = TrafficStats.getMobileRxBytes();
		long currentMobile_Tx = TrafficStats.getMobileTxBytes();
		long currentMobile_Rp = TrafficStats.getMobileRxPackets();
		long currentMobile_Tp = TrafficStats.getMobileTxPackets();

		long currentAll_Rx = TrafficStats.getTotalRxBytes();
		long currentAll_Tx = TrafficStats.getTotalTxBytes();
		long currentAll_Rp = TrafficStats.getTotalRxPackets();
		long currentAll_Tp = TrafficStats.getTotalTxPackets();

		if (currentMobile_Rx - Global.last_Mobile_Rx >= 0
				&& Global.last_Mobile_Rx > 0) {
			Global.Total_Mobile_Rx += currentMobile_Rx - Global.last_Mobile_Rx;
		}
		if (currentMobile_Tx - Global.last_Mobile_Tx >= 0
				&& Global.last_Mobile_Tx > 0) {
			Global.Total_Mobile_Tx += currentMobile_Tx - Global.last_Mobile_Tx;
		}

		if (currentMobile_Rp - Global.last_Mobile_Rp >= 0
				&& Global.last_Mobile_Rp > 0) {
			Global.Total_Mobile_Rp += currentMobile_Rp - Global.last_Mobile_Rp;
		}
		if (currentMobile_Tp - Global.last_Mobile_Tp >= 0
				&& Global.last_Mobile_Tp > 0) {
			Global.Total_Mobile_Tp += currentMobile_Tp - Global.last_Mobile_Tp;
		}

		Global.last_Mobile_Rx = currentMobile_Rx;
		Global.last_Mobile_Tx = currentMobile_Tx;
		Global.last_Mobile_Rp = currentMobile_Rp;
		Global.last_Mobile_Tp = currentMobile_Tp;

		if (currentAll_Rx - Global.last_All_Rx >= 0 && Global.last_All_Rx > 0) {
			Global.Total_All_Rx += currentAll_Rx - Global.last_All_Rx;
		}
		if (currentAll_Tx - Global.last_All_Tx >= 0 && Global.last_All_Tx > 0) {
			Global.Total_All_Tx += currentAll_Tx - Global.last_All_Tx;
		}

		if (currentAll_Rp - Global.last_All_Rp >= 0 && Global.last_All_Rp > 0) {
			Global.Total_All_Rp += currentAll_Rp - Global.last_All_Rp;
		}
		if (currentAll_Tp - Global.last_All_Tp >= 0 && Global.last_All_Tp > 0) {
			Global.Total_All_Tp += currentAll_Tp - Global.last_All_Tp;
		}
		Global.last_All_Rx = currentAll_Rx;
		Global.last_All_Tx = currentAll_Tx;
		Global.last_All_Rp = currentAll_Rp;
		Global.last_All_Tp = currentAll_Tp;
	}

	private void SyncDB() {
		Intent intent = new Intent(Global.ACTION_UPDATE_TASKLIST);
		sendBroadcast(intent);

		SharedPreferences sPreferences = getSharedPreferences(Global.PREFS,
				Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = sPreferences.edit();
		editor.putLong("total_mobile_rx", Global.Total_Mobile_Rx);
		editor.putLong("total_mobile_tx", Global.Total_Mobile_Tx);
		editor.putLong("last_mobile_rx", Global.last_Mobile_Rx);
		editor.putLong("last_mobile_tx", Global.last_Mobile_Tx);
		editor.commit();
	}

	private void resetLastMobileBytes() {
		if (mTaskInfos == null)
			return;

		for (int i = 0; i < mTaskInfos.size(); i++) {
			TaskInfo tInfo = mTaskInfos.get(i);
			tInfo.m_lMobile_last_Rx = TrafficStats
					.getUidRxBytes(tInfo.getUID());
			tInfo.m_lMobile_last_Tx = TrafficStats
					.getUidTxBytes(tInfo.getUID());
		}

		Global.last_Mobile_Rx = TrafficStats.getMobileRxBytes();
		Global.last_Mobile_Tx = TrafficStats.getMobileTxBytes();
	}

	private boolean wifi_IsConnected() {
		try {
			if (Global.cm != null) {

				// 获取网络连接管理的对象
				NetworkInfo info = Global.cm.getActiveNetworkInfo();

				if (info != null && info.isConnected()) {
					int nType = info.getType();
					if (nType == ConnectivityManager.TYPE_WIFI
							|| nType == ConnectivityManager.TYPE_WIMAX) {
						// 判断当前网络是否已经连接
						if (info.getState() == NetworkInfo.State.CONNECTED) {
							return true;
						}
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			Log.v("get connection state error", e.toString());
		}
		return false;
	}

	private boolean mobile_IsConnected() {
		try {
			if (Global.cm != null) {

				// 获取网络连接管理的对象
				NetworkInfo info = Global.cm.getActiveNetworkInfo();

				if (info != null && info.isConnected()) {
					int nType = info.getType();
					if (nType == ConnectivityManager.TYPE_MOBILE
							|| nType == ConnectivityManager.TYPE_MOBILE_DUN
							|| nType == ConnectivityManager.TYPE_MOBILE_HIPRI
							|| nType == ConnectivityManager.TYPE_MOBILE_MMS
							|| nType == ConnectivityManager.TYPE_MOBILE_SUPL) {
						// 判断当前网络是否已经连接
						if (info.getState() == NetworkInfo.State.CONNECTED) {
							return true;
						}
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			Log.v("get connection state error", e.toString());
		}
		return false;
	}

	private class ConnectionMonitor extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			// Log.d("Connection", "Connection Changed");

			if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {

				boolean noConnectivity = intent.getBooleanExtra(
						ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
				NetworkInfo aNetworkInfo = (NetworkInfo) intent
						.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

				if (!noConnectivity) {
					switch (aNetworkInfo.getType()) {
					case ConnectivityManager.TYPE_MOBILE:
					case ConnectivityManager.TYPE_MOBILE_DUN:
					case ConnectivityManager.TYPE_MOBILE_HIPRI:
					case ConnectivityManager.TYPE_MOBILE_MMS:
					case ConnectivityManager.TYPE_MOBILE_SUPL: {
						m_bIsWifiConnected = false;
						resetLastMobileBytes();
					}
						break;

					case ConnectivityManager.TYPE_WIFI:
						m_bIsWifiConnected = true;
						break;

					default:
						break;
					}
				} else {
					if ((aNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
							|| (aNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI)) {
						// Handle disconnected case
					}
				}
			} else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
				m_bScreenOff = true;
				while (doRefresh.cancel())
					;
				updateTimer.cancel();
				doRefresh = new RefreshTimerTask();
				updateTimer = new Timer("taskTrafficRefresh");
				updateTimer.schedule(doRefresh, 0L, 30000L);
				Log.e("Timer", "reSchedule");
			} else if (action.equals(Intent.ACTION_SCREEN_ON)) {
				m_bScreenOff = false;
				while (doRefresh.cancel())
					;
				updateTimer.cancel();
				doRefresh = new RefreshTimerTask();
				updateTimer = new Timer("taskTrafficRefresh");
				updateTimer.schedule(doRefresh, 0L, 10000L);
				Log.e("Timer", "reSchedule");
			}
		}
	}

	private synchronized void startMonitoringConnection() {
		IntentFilter aFilter = new IntentFilter(
				ConnectivityManager.CONNECTIVITY_ACTION);
		registerReceiver(mConnectionReceiver, aFilter);
		aFilter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
		registerReceiver(mConnectionReceiver, aFilter);
		aFilter = new IntentFilter(Intent.ACTION_SCREEN_ON);
		registerReceiver(mConnectionReceiver, aFilter);
	}

	private synchronized void stopMonitoringConnection() {
		unregisterReceiver(mConnectionReceiver);
	}

	private class RefreshTimerTask extends TimerTask {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			if (!InitialFinished)
				return;

			// m_bIsWifiConnected = !m_bIsWifiConnected;
			if (m_bIsWifiConnected) {
				// return;
			}
			if (!m_bScreenOff || (m_bScreenOff && m_bIsNetworkActiveChanged)) {
				long begin = System.currentTimeMillis();
				Log.e("BEGIN", String.valueOf(begin));

				RefreshList();
				m_bListUpdated = true;
				m_bIsNetworkActiveChanged = false;
				long end = System.currentTimeMillis();
				Log.e("END", String.valueOf(end));
				Log.e("DURING", String.valueOf(end - begin));
				Log.e("Service", "Refresh!");
			} else {
				Log.e("Service", "Network Is Inactive!");
			}
		}

	}

}
